#include "FPCH.h"

#include "FKerningTable.h"

namespace Font
{

	KerningTable::KerningTable(Library* a_Library)
	{
		m_Library = a_Library;	
	}
	
	KerningTable::~KerningTable()
	{
		for (std::vector<KerningList*>::iterator it = m_List.begin(); it != m_List.end(); )
		{
			for (std::vector<KerningEntry*>::iterator jt = (*it)->entries.begin(); jt != (*it)->entries.end(); )
			{
				delete *jt;
				jt = (*it)->entries.erase(jt);
			}

			delete *it;
			it = m_List.erase(it);
		}
	}

	void KerningTable::AddEntry(unsigned int a_GlyphLeft, unsigned int a_GlyphRight, int a_AmountX)
	{
		KerningList* list = _GetList(a_GlyphLeft);
		if (!list)
		{
			list = new KerningList;
			list->glyph = a_GlyphLeft;
			m_List.push_back(list);
		}

		KerningEntry* entry = NULL;
		for (size_t i = 0; i < list->entries.size(); i++)
		{
			if (list->entries[i]->glyph_right == a_GlyphRight)
			{
				entry = list->entries[i];
				break;
			}
		}
		if (!entry) 
		{ 
			entry = new KerningEntry; 
			entry->glyph_right = a_GlyphRight;
			list->entries.push_back(entry);
		}

		entry->amount_x = a_AmountX;
	}

	int KerningTable::GetKerning(unsigned int a_GlyphLeft, unsigned int a_GlyphRight)
	{
		KerningList* list = _GetList(a_GlyphLeft);
		if (!list) { return 0; }

		for (size_t i = 0; i < list->entries.size(); i++)
		{
			if (list->entries[i]->glyph_right == a_GlyphRight)
			{
				return list->entries[i]->amount_x;
			}
		}

		return 0;
	}

	KerningTable::KerningList* KerningTable::_GetList(unsigned int a_Glyph)
	{
		KerningList* result = NULL;

		for (size_t i = 0; i < m_List.size(); i++)
		{
			if (m_List[i]->glyph == a_Glyph)
			{
				result = m_List[i];
				break;
			}
		}

		return result;
	}

}; // namespace Font